<template>
    <el-breadcrumb :separator-icon="ArrowRight">
    <el-breadcrumb-item :to="{ path: '/' }">首页(登录)</el-breadcrumb-item>
    <el-breadcrumb-item>授权中心管理</el-breadcrumb-item>
    <el-breadcrumb-item>权限管理</el-breadcrumb-item>
  </el-breadcrumb>
    <div>
       <el-card style="margin-top: 10px;">
          <el-form :inline="true" :model="searchData" class="demo-form-inline">
    <el-form-item label="权限名称">
      <el-input v-model="searchData.permissionName" placeholder="权限名称" clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="getPermissions">查询</el-button>
      <el-button type="success" @click="addPermission">添加</el-button>
    </el-form-item>
  </el-form>
       </el-card>
       <el-card style="margin-top: 10px;" shadow="hover">
        <el-breadcrumb-item>权限列表</el-breadcrumb-item>
         <el-table 
           :data="permissionData" 
           border 
           style="width: 100%" 
           :row-style="{ height: '60px' }"
           stripe
           v-loading="loading"
           element-loading-text="加载中..."
           element-loading-spinner="el-icon-loading"
           element-loading-background="rgba(0, 0, 0, 0.8)"
         >
    <el-table-column type="index" label="序号" align="center" width="80" :index="(index: number) => (page.PageIndex - 1) * page.PageSize + index + 1">
      <template #default="scoped">
        <el-tag type="info" size="small" effect="plain">{{ (page.PageIndex - 1) * page.PageSize + scoped.$index + 1 }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="permissionName" label="权限名称" align="center" min-width="150">
      <template #default="scoped">
        <div class="permission-name">
          <!-- <el-icon style="margin-right: 8px; color: #409eff;"><Key /></el-icon> -->
          <span style="font-weight: 500; color: #303133;">{{ scoped.row.permissionName }}</span>
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="permissionUrl" label="权限URL" align="center" min-width="200">
      <template #default="scoped">
        <div class="permission-url">
          <el-icon style="margin-right: 8px; color: #67c23a;"><Link /></el-icon>
          <el-text type="info" size="small">{{ scoped.row.permissionUrl }}</el-text>
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="status" label="状态" align="center" width="100">
          <template #default="scoped">
            <el-tag v-if="scoped.row.status == '0'" type="success" effect="dark" size="small">
              <el-icon style="margin-right: 4px;"><Check /></el-icon>
              启用
            </el-tag>
            <el-tag v-else type="danger" effect="dark" size="small">
              <el-icon style="margin-right: 4px;"><Close /></el-icon>
              禁用
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center" width="180">
            <template v-slot="scoped">
              <div class="create-time">
                <el-icon style="margin-right: 8px; color: #909399;"><Clock /></el-icon>
                <el-text type="info" size="small">{{ moment(scoped.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}</el-text>
              </div>
        </template>
    </el-table-column>
    <el-table-column label="操作" align="center" width="160" fixed="right">
        <template #default="scoped">
            <div class="action-buttons">
              <el-button 
                type="primary" 
                size="small" 
                @click="editPermission(scoped.row)"
                :icon="Edit"
                plain
                round
              >
                编辑
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="deletePermission(scoped.row.permissionId)"
                :icon="Delete"
                plain
                round
              >
                删除
              </el-button>
            </div>
        </template>
    </el-table-column>
  </el-table>
  <div class="pagination-container">
    <el-pagination
      v-model:current-page="page.PageIndex"
      v-model:page-size="page.PageSize"
      :page-sizes="[5, 10, 20, 50]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.totalCount"
      class="custom-pagination"
    />
  </div>
       </el-card>
       
       <!-- 添加/编辑权限弹窗 -->
       <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" draggable>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="addRules" label-width="100px">
            <el-form-item label="权限名称" prop="permissionName">
                <el-input v-model="ruleForm.permissionName" placeholder="请输入权限名称" />
            </el-form-item>
            <el-form-item label="权限描述" prop="permissionUrl">
                <el-input v-model="ruleForm.permissionUrl" placeholder="请输入权限描述" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
            </span>
        </template>
    </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref,watch } from 'vue'
import { ElMessageBox } from 'element-plus';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import { useCounterStore } from "@/stores/counter"
import { dataRead,dataWrite } from '@/Utils/Http';
import { ArrowRight, Key, Link, Check, Close, Clock, Edit, Delete } from '@element-plus/icons-vue'
import moment from 'moment';

// 类型定义
interface RuleForm  {
    permissionId: number;
    permissionName: string;
    permissionUrl: string;
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    permissionId:0,
    permissionName: '',
    permissionUrl: ''
})

// 变量初始化
const counter = useCounterStore();
const router = useRouter();
const loading = ref(false);
const permissionData = ref<any>([]);
const searchData = reactive({
    permissionName: ''
});
const page = reactive({
    PageIndex: 1,
    PageSize: 5,
    totalCount: 0,
    pageCount: 0
});

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('添加权限');
const formRef = ref<FormInstance>();
// const formData = reactive<FormData>({
//     permissionId: 0,
//     permissionName: '',
//     permissionUrl: ''
// });

// 添加表单验证规则（需要非空验证）
const addRules  = reactive<FormRules<RuleForm>>({
    permissionName: [
        { required: true, message: '请输入权限名称', trigger: 'blur' }
    ],
    permissionUrl: [
        { required: true, message: '请输入权限URL', trigger: 'blur' }
    ]
});

// 编辑表单验证规则（不需要非空验证）
const editRules  = reactive<FormRules<RuleForm>>({});

// 生命周期钩子
onMounted(() => {
    getPermissions();
});

// 获取权限列表
const getPermissions = () => {
    loading.value = true;
    // 模拟数据，实际项目中应替换为真实API调用
    // 这里使用模拟数据以便页面展示
    // permissionData.value = [
    //     { id: 1, name: '试题管理', url: '//' },
    //     { id: 2, name: '考试', url: '//' },
    //     { id: 3, name: '查看成绩', url: '//' },
    //     { id: 4, name: '成绩分析', url: '//' }
    // ];
    
    // 实际API调用代码如下（注释掉）
    dataRead.get('/BaseData/PermissionQuery', {
        params: {
            permissionName: searchData.permissionName,
            PageIndex: page.PageIndex,
            PageSize: page.PageSize
        } 
    }).then(res => {
        permissionData.value = res.data.data.data;
        page.totalCount = res.data.data.totalCount;
        page.pageCount = res.data.data.pageCount;
    }).catch(err => {
        ElMessage.error('获取权限列表失败');
        console.error(err);
    }).finally(() => {
        loading.value = false;
    });
};
watch(page, () => {
    getPermissions()
})

// 添加权限
const addPermission = () => {
    dialogTitle.value = '添加权限';
    ruleForm.permissionId = 0;
    ruleForm.permissionName = '';
    ruleForm.permissionUrl = '';
    dialogVisible.value = true;
};

// 编辑权限
const editPermission = (row: any) => {
    dialogTitle.value = '编辑权限';
   Object.assign(ruleForm,row)
    dialogVisible.value = true;
};

// 删除权限
const deletePermission = (permissionId: any) => {
    ElMessageBox.confirm(
        '确定要删除该权限吗？',
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        /* 实际API调用代码如下（注释掉）*/
        dataWrite.post('/BaseData/DelPermission?PermissionId='+permissionId).then(res => {
            if (res.data.code==500) {
                ElMessage.success('删除成功');
                getPermissions(); // 重新获取列表
            } else {
                ElMessage.error(res.data.message || '删除失败');
            }
        }).catch(err => {
            ElMessage.error('删除失败');
            console.error(err);
        });
        
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
};


// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
        console.log('submit!')
        if (ruleForm.permissionId == 0)
        {
            dataWrite.post('/BaseData/AddPermission',ruleForm).then(res => {
                if (res.data.code == 300)
                {
                    ElMessage.success('添加成功')
                    dialogVisible.value = false
                    getPermissions()
                }
                else if (res.data.data == -1)
                {
                    ElMessage.error(res.data.message)
                }
                else
                {
                 ElMessage.error('添加失败')
            }
          })
        }
        //修改
        else
        {
             dataWrite.post('/BaseData/UpdPermission',ruleForm).then(res => {
                if (res.data.code == 400)
                {
                    ElMessage.success('修改成功')
                    dialogVisible.value = false
                    getPermissions()
                }
                 else if (res.data.data == -1)
                {
                    ElMessage.error(res.data.message)
                }
                else
                {
                 ElMessage.error('修改失败')
            }
          })
       }
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}


</script>

<style scoped>
/* 表格美化样式 */
.permission-name {
  display: flex;
  align-items: center;
  justify-content: center;
}

.permission-url {
  display: flex;
  align-items: center;
  justify-content: center;
}

.create-time {
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
}

/* 分页容器样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 20px 0;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 8px;
}

.custom-pagination {
  background: rgb(233, 233, 233);
  padding: 10px 20px;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 表格悬停效果 */
:deep(.el-table__row:hover) {
  background-color: #f0f9ff !important;
  transform: translateY(-1px);
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 表格头部样式 */
:deep(.el-table__header-wrapper) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

:deep(.el-table__header th) {
  background: transparent !important;
  color: white !important;
  font-weight: bold !important;
  border: none !important;
}

:deep(.el-table__header th .cell) {
  color: rgb(59, 33, 33) !important;
  /* font-weight: bold !important; */
}

/* 表格边框美化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-table td) {
  border-bottom: 1px solid #f0f0f0;
}

/* 按钮美化 */
:deep(.el-button) {
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 标签美化 */
:deep(.el-tag) {
  border-radius: 12px;
  font-weight: 500;
  padding: 4px 12px;
}

/* 卡片阴影效果 */
:deep(.el-card) {
  border-radius: 12px;
  transition: all 0.3s ease;
}

:deep(.el-card:hover) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

/* 加载动画美化 */
:deep(.el-loading-mask) {
  background-color: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(4px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }
  
  .pagination-container {
    padding: 15px 10px;
  }
  
  .custom-pagination {
    padding: 8px 15px;
  }
}
</style>